import React, { useEffect, useState, useRef, useContext } from 'react'
import { Button, Table, message, Form, Input } from 'antd';
import axios from 'axios';


export default function Category() {
  const [categoryList, setCategoryList] = useState([])
  useEffect(() => {
    axios.get('/categories').then(res => {
      console.log(res)
      setCategoryList(res.data)
    })
  }, [])

  // 使用了行内表单
  const EditableContext = React.createContext(null);
  const EditableRow = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
      <Form form={form} component={false}>
        <EditableContext.Provider value={form}>
          <tr {...props} />
        </EditableContext.Provider>
      </Form>
    );
  };
  const EditableCell = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
  }) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef(null);
    const form = useContext(EditableContext);
    useEffect(() => {
      if (editing) {
        inputRef.current.focus();
      }
    }, [editing]);
    const toggleEdit = () => {
      setEditing(!editing);
      form.setFieldsValue({
        [dataIndex]: record[dataIndex],
      });
    };
    const save = async () => {
      try {
        const values = await form.validateFields();
        toggleEdit();
        handleSave({
          ...record,
          ...values,
        });
      } catch (errInfo) {
        console.log('Save failed:', errInfo);
      }
    };
    let childNode = children;
    if (editable) {
      childNode = editing ? (
        <Form.Item
          style={{
            margin: 0,
          }}
          name={dataIndex}
          rules={[
            {
              required: true,
              message: `${title} is required.`,
            },
          ]}
        >
          <Input ref={inputRef} onPressEnter={save} onBlur={save} />
        </Form.Item>
      ) : (
        <div
          className="editable-cell-value-wrap"
          style={{
            paddingRight: 24,
          }}
          onClick={toggleEdit}
        >
          {children}
        </div>
      );
    }
    return <td {...restProps}>{childNode}</td>;
  };

  // 编辑单元格主要功能
  const handleSave = (value) => {
    // console.log(value)
    setCategoryList(categoryList.map(item => {
      if (item.id === value.id) {
        return {
          id: value.id,
          title: value.title,
          value: value.title
        }
      }
      return item
    }))

    axios.patch(`/categories/${value.id}`, {
      title: value.title,
      value: value.title
    })
  }

  // 表格数据
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      // render: (title, item) => <a href={`#/news-manage/preview/${item.id}`}>{title}</a>
    },
    {
      title: '栏目名称',
      dataIndex: 'title',
      onCell: (record) => ({
        record,
        editable: true,
        dataIndex: "title",
        title: "栏目名称",
        handleSave,
      }),
    },
    {
      title: '操作',
      render: (item) => {
        return <div>
          <Button type='primary' danger onClick={() => deleteCategory(item)}>删除</Button>
        </div>
      }
    },
  ];

  // 删除分类
  const deleteCategory = (item) => {
    // console.log(item)
    setCategoryList(categoryList.filter(i => i.id !== item.id))
    axios.delete(`/categories/${item.id}`).then(res => {
      message.success('删除成功')
    })
  }



  return (
    <div>
      <Table components={{
        body: {
          row: EditableRow,
          cell: EditableCell,
        },
      }} dataSource={categoryList} columns={columns} rowKey={item => item.id} pagination={{ pageSize: 5 }} />;
    </div>

  )
}
